//
//  set_ViewController.m
//  SoundPill
//
//  Created by 宋鹏鹏 on 15/3/30.
//  Copyright (c) 2015年 宋旭东. All rights reserved.
//

#import "set_ViewController.h"
#import "user_editController.h"
#import "settingResetPwViewController.h"
#import "accountDetailViewController.h"
#import "AddTagViewController.h"
#import "feedback_Controller.h"
#import "playerAddressViewController.h"
#import "set_nameitem.h"
#import "set_nolineItem.h"
#import "UIViewExt.h"
#import "AFNetworking.h"
#import "SDWebImageManager.h"
#import "UIImageView+WebCache.h"
#import "MobClick.h"
#import <CoreLocation/CoreLocation.h>
#import "AppDelegate.h"
#import "JCAlertView.h"
@interface set_ViewController ()<UIAlertViewDelegate>
{
    UIScrollView *_scrollview;
    
    set_nameitem *_setNameItem;
    
    set_nameitem *_messagePush;
    //关于我们
    set_nameitem *_aboutUs;
    //清理缓存
    set_nameitem *_clearCache;
    //符点助手
    set_nameitem *_assistant;
    //给我们打分
    set_nameitem *_givesScore;
    //用户协定
    set_nameitem *_userAgreement;
    UISwitch   *_wifiSwich;
    UISwitch   *_savePhoto;
    //关注标签
    set_nolineItem *_setLinkItem;
    //提现
    set_nameitem *tixianItem;
    UIView *shareView;
    UIButton *_cancelItem;
}
- (void)loadSetView;
@end

@implementation set_ViewController
- (instancetype)init
{
    self = [super init];
    if (self) {
        self.hidesBottomBarWhenPushed = YES;
        UIButton *back = [UIButton buttonWithType:UIButtonTypeCustom];
        [back setFrame:CGRectMake(0, 0, 30, 30)];
        [back setImage:[UIImage imageNamed:@"backButton"] forState:UIControlStateNormal];
        [back addTarget:self action:@selector(backTo) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:back];
        self.navigationItem.leftBarButtonItem = backItem;
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeSelfAvatar:) name:@"changMyselfAvatar" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeAccount:) name:@"changeAccount" object:nil];
    }
    return self;
}
- (void)changeSelfAvatar:(NSNotification *)notification
{
    UIImage *img = notification.object;
    _setNameItem.headImage.image = img;
}
- (void)changeAccount:(NSNotification *)notification
{
    NSString *str = notification.object;
    _account = [NSString stringWithFormat:@"%.2f",_account.floatValue - str.floatValue];
    tixianItem.numLable.text = _account;
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    [MobClick beginLogPageView:@"设置"];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:YES];
     [MobClick endLogPageView:@"设置"];
}
- (void)viewDidLoad {
    [super viewDidLoad];
     self.title=@"设置";
    UIBarButtonItem *backItem=[[UIBarButtonItem alloc]init];
    backItem.title=@"";
    self.navigationItem.backBarButtonItem = backItem;
    self.navigationController.navigationBar.translucent = NO;
    self.view.backgroundColor=[UIColor whiteColor];
    
    _scrollview = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height - 64)];
    _scrollview.contentSize = CGSizeMake(self.view.width, self.view.height + 40);
    _scrollview.backgroundColor = [UIColor clearColor];
    _scrollview.showsVerticalScrollIndicator = NO;

    [self.view addSubview:_scrollview];
    
    [self loadSetView];
}

- (void)loadSetView{
    CGFloat _height = 44;
    if ([UIScreen mainScreen].bounds.size.width == 320) {
        _height = 35;
    }
    
    UIView *person = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.width, _height)];
    person.backgroundColor = [UIColor whiteColor];
    UILabel *person1 = [[UILabel alloc]initWithFrame:CGRectMake(17, (_height - 26) / 2, 63, 26)];
    person1.text = @"个人";
    person1.textColor = [UIColor grayColor];
    person1.font = [UIFont systemFontOfSize:14];
    [person addSubview:person1];
    UIImageView *personLine = [[UIImageView alloc] initWithFrame:CGRectMake(0, person.bounds.size.height, self.view.width, 1)];
    personLine.image = [UIImage imageNamed:@"gray_line"];
    [person addSubview:personLine];
    
    [_scrollview addSubview:person];
//本地头像
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *headImageFilePath = [documentsDirectory stringByAppendingPathComponent:@"selfPhoto.jpg"];
    UIImage *selfPhoto = [UIImage imageWithContentsOfFile:headImageFilePath];//读取图片文件
    //
    _setNameItem = [[set_nameitem alloc] initWithFrame:CGRectMake(0, _height, self.view.width, _height)];
    
    NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
    //读取字典类型NSDictionary类型的数据
    NSDictionary *myDictionary = [userDefaultes dictionaryForKey:@"myDictionary"];
    
    _setNameItem.title = [myDictionary objectForKey:@"username"];
    if ([[myDictionary valueForKey:@"avatar"] isKindOfClass:[NSNull class]]) {
        _setNameItem.headImage.image = selfPhoto;
    } else {
        [_setNameItem.headImage setImageWithURL:[NSURL URLWithString:[myDictionary valueForKey:@"avatar"]]];
    }
    
    [_scrollview addSubview:_setNameItem];
    //
    [_setNameItem addTarget:self action:@selector(setNameClick) forControlEvents:UIControlEventTouchUpInside];
//关注标签
    _setLinkItem = [[set_nolineItem alloc]initWithFrame:CGRectMake(0, 2*_height, self.view.width, _height)];
    
    _setLinkItem.title = @"已关注标签";
    
    [_scrollview addSubview:_setLinkItem];
    [_setLinkItem addTarget:self action:@selector(setLinkClick) forControlEvents:UIControlEventTouchUpInside];

    tixianItem = [[set_nameitem alloc] initWithFrame:CGRectMake(0, 3*_height, self.view.width, _height)];
    tixianItem.title = @"余额&明细";
    tixianItem.numLable.text = [NSString stringWithFormat:@"¥ %@",_account];//@"¥1.11";
//    tixianItem.numLable.textColor = [UIColor colorWithRed:0.969 green:0.306 blue:0.251 alpha:1.00];
    [tixianItem addTarget:self action:@selector(accountClick) forControlEvents:UIControlEventTouchUpInside];
    [_scrollview addSubview:tixianItem];
    
    set_nolineItem *contItem = [[set_nolineItem alloc] initWithFrame:CGRectMake(0, 4 * _height, self.view.width, _height)];
    contItem.title = @"联系人信息";
    [contItem addTarget:self action:@selector(addressClick:) forControlEvents:UIControlEventTouchUpInside];
    [_scrollview addSubview:contItem];
    
    UIView *preferences = [[UIView alloc]initWithFrame:CGRectMake(0, _height * 5, self.view.width, _height)];
    preferences.backgroundColor = [UIColor whiteColor];
    [_scrollview addSubview:preferences];
    
    UILabel *preferences1 = [[UILabel alloc]initWithFrame:CGRectMake(17, (_height - 26) / 2, 120, 26)];
    preferences1.text = @"系统偏好";
    preferences1.textColor = [UIColor grayColor];
    preferences1.font = [UIFont systemFontOfSize:14];
    [preferences addSubview:preferences1];
    
    UIImageView *preferencesLine = [[UIImageView alloc] initWithFrame:CGRectMake(0, preferences.frame.size.height - 2, self.view.width, 1)];
    preferencesLine.image = [UIImage imageNamed:@"gray_line"];
    [preferences addSubview:preferencesLine];
    
    //仅Wi-Fi环境播放按钮
    UIView *wifiView = [[UIView alloc]initWithFrame:CGRectMake(0, _height * 6, self.view.width, _height)];
    wifiView.backgroundColor = [UIColor whiteColor];
    
    UIImage *downImg = [UIImage imageNamed:@"gray_line"];
    UIImageView *downDivider = [[UIImageView alloc] initWithImage:downImg];
    downDivider.bounds = CGRectMake(0,0, self.view.width, 1 );
    downDivider.center = CGPointMake(self.view.width/2, _height-0.5);
    [wifiView addSubview:downDivider];

    UILabel *wifilabel =[[UILabel alloc]initWithFrame:CGRectMake(17, 0, 200, _height)];
    wifilabel.backgroundColor = [UIColor clearColor];
    wifilabel.text = @"仅WiFi环境下播放";
    wifilabel.textColor = [UIColor blackColor];
    wifilabel.font = [UIFont systemFontOfSize:17];
    
    [wifiView addSubview:wifilabel];
    _wifiSwich = [[UISwitch alloc]initWithFrame:CGRectMake(self.view.width-62, 5, 30, 20)];
    
//    _wifiSwich.center = CGPointMake(_wifiSwich.center.x, _wifiSwich.center.y);
//    _wifiSwich.onTintColor = [UIColor colorWithRed:20/255.0 green:155/255.0 blue:213/255.0 alpha:1.0];
    _wifiSwich = [[UISwitch alloc]initWithFrame:CGRectZero];
    if (_height == 35) {
        _wifiSwich.frame = CGRectMake(self.view.width-62, 0, 30, 20);
        _wifiSwich.transform = CGAffineTransformMakeScale(0.75, 0.75);
    } else {
        _wifiSwich.frame = CGRectMake(self.view.width-62, 5, 30, 20);
    }
    [wifiView addSubview:_wifiSwich];
    [_scrollview addSubview:wifiView];
    
    //
    NSString *isWiFiPlay = [userDefaultes stringForKey:@"isWiFiPlay"];
    if ([isWiFiPlay isEqualToString:@"0"]) {
        _wifiSwich.on = NO;
    }else if([isWiFiPlay isEqualToString:@"1"]){
        _wifiSwich.on = YES;
    }

    
    [_wifiSwich addTarget:self action:@selector(wifiSwichClick) forControlEvents:UIControlEventValueChanged];

    
    //
    UIView *otherImg = [[UIView alloc]initWithFrame:CGRectMake(0,_height * 7, self.view.width, _height)];
    otherImg.backgroundColor = [UIColor whiteColor];
    UILabel *otherImg1 = [[UILabel alloc]initWithFrame:CGRectMake(17, 9, 160, 26)];
    otherImg1.text = @"其他";
    otherImg1.textColor = [UIColor grayColor];
    otherImg1.font = [UIFont systemFontOfSize:14];
    UIImageView *blackline = [[UIImageView alloc] initWithFrame:CGRectMake(0, otherImg.frame.size.height, self.view.width, 1)];
    blackline.image = [UIImage imageNamed:@"gray_line"];
    [otherImg addSubview:otherImg1];
    [otherImg addSubview:blackline];
    [_scrollview addSubview:otherImg];

    set_nolineItem *resetPassword= [[set_nolineItem alloc] initWithFrame:CGRectMake(0, _height * 8, self.view.width, _height)];
    resetPassword.title = @"修改密码";
    [_scrollview addSubview:resetPassword];
    [resetPassword addTarget:self action:@selector(resetPasswordClick) forControlEvents:UIControlEventTouchUpInside];
    //清理缓存（多少MB）
    _clearCache = [[set_nameitem alloc]initWithFrame:CGRectMake(0, 9*_height, self.view.width, _height)];
    _clearCache.title = @"清理缓存";
//    _clearCache.numLable.textColor = [UIColor blackColor];
    if ([ self filePath ]>0) {
        _clearCache.numLable.text = [NSString stringWithFormat:@"%.2fM",[self filePath]];
    }else
    {
        _clearCache.numLable.text = nil;//[NSString stringWithFormat:@"%.2fM",[self filePath]];
    }
    
    [_scrollview addSubview:_clearCache];
    //
    [_clearCache addTarget:self action:@selector(clearCacheClick) forControlEvents:UIControlEventTouchUpInside];
    
    //意见反馈
    UIButton *feedback = [[UIButton alloc]initWithFrame:CGRectMake(self.view.width*0.04 , _height * 11, self.view.width*0.92, 41)];
    feedback.backgroundColor = [UIColor blackColor];
    [feedback setTitle:@"意见反馈" forState:UIControlStateNormal];
    [feedback setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    feedback.layer.borderColor = [UIColor blackColor].CGColor;
    feedback.layer.borderWidth = 2;
    [_scrollview addSubview:feedback];
    [feedback addTarget:self action:@selector(feedbackClick) forControlEvents:UIControlEventTouchUpInside];
    //退出按钮
    UIButton *exitBtn = [[UIButton alloc]initWithFrame:CGRectMake(self.view.width*0.04 , feedback.bottom + 10, self.view.width*0.92, 41)];
    exitBtn.backgroundColor = [UIColor whiteColor];
    [exitBtn setTitle:@"退出登录" forState:UIControlStateNormal];
    [exitBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    exitBtn.layer.borderColor = [UIColor blackColor].CGColor;
    exitBtn.layer.borderWidth = 2;
    [exitBtn setTitleColor:[UIColor blueColor] forState:UIControlStateHighlighted];
    [_scrollview addSubview:exitBtn];
    
    [exitBtn addTarget:self action:@selector(exitClick) forControlEvents:UIControlEventTouchUpInside];
//    if ([UIScreen mainScreen].bounds.size.width != 320) {
        UILabel *vision = [[UILabel alloc] initWithFrame:CGRectMake(self.view.width*0.04, _scrollview.bottom - 20, exitBtn.frame.size.width, 20)];
//        vision.center = CGPointMake(self.view.frame.size.width / 2, _scrollview.frame.size.height - 30);
        NSString *visionString = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
        vision.text = [NSString stringWithFormat:@"V %@", visionString];
        vision.textAlignment = NSTextAlignmentCenter;
        vision.textColor = [UIColor blackColor];
        [_scrollview addSubview:vision];
//    }
   
}
//设置用户
- (void)setNameClick
{
    user_editController *userEditVC = [[user_editController alloc]init];
    [self.navigationController pushViewController:userEditVC animated:YES];
}
//设置标签
- (void)setLinkClick
{
    AddTagViewController *atenTag = [[AddTagViewController alloc] initWithTitle:@"已关注标签"];
    [self.navigationController pushViewController:atenTag animated:YES];
}
//提现
- (void)accountClick
{
    accountDetailViewController *accountDetail = [[accountDetailViewController alloc] init];
    accountDetail.balance = _account;
    [self.navigationController pushViewController:accountDetail animated:YES];
}
//收件人信息
- (void)addressClick:(id)sender
{
    playerAddressViewController *addressVC = [[playerAddressViewController alloc] init];
    [self.navigationController pushViewController:addressVC animated:YES];
}
//wifi
- (void)wifiSwichClick
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    //存储时，除NSNumber类型使用对应的类型意外，其他的都是使用setObject:forKey:
    if (_wifiSwich.on == YES) {
        [userDefaults setObject:@"1" forKey:@"isWiFiPlay"];
        
    }else{
        [userDefaults setObject:@"0" forKey:@"isWiFiPlay"];
        
    }
    [userDefaults synchronize];

    //
}
//关于我们
- (void)aboutUsClick
{

}
//清理缓存
- (void)clearCacheClick
{   //
    [JCAlertView showTwoButtonsWithTitle:@"清理缓存" Message:@"确定要清理缓存么?" ButtonType: JCAlertViewButtonTypeCancel ButtonTitle:@"取消" Click:^{
        
    } ButtonType:JCAlertViewButtonTypeDefault ButtonTitle:@"确定" Click:^{
         [self clearFile];
    }];
}
//修改密码
- (void)resetPasswordClick
{
    settingResetPwViewController *settingPW = [[settingResetPwViewController alloc] init];
    [self.navigationController pushViewController:settingPW animated:YES];
}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        
        
    }else if (buttonIndex == 1){
       
    }
}


#pragma mark- 清理缓存
//1:首先我们计算一下 单个文件的大小
- ( long long ) fileSizeAtPath:( NSString *) filePath{
    
    NSFileManager * manager = [ NSFileManager defaultManager ];
    
    if ([manager fileExistsAtPath :filePath]){
        
        return [[manager attributesOfItemAtPath :filePath error : nil ] fileSize ];
        
    }
    return 0 ;
}

//2: 遍历文件夹获得文件夹大小，返回多少 M

- ( float ) folderSizeAtPath:( NSString *) folderPath{
    
    NSFileManager * manager = [ NSFileManager defaultManager ];
    
    if (![manager fileExistsAtPath :folderPath]) return 0 ;
    
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath :folderPath] objectEnumerator ];
    NSString * fileName;
    
    long long folderSize = 0 ;
    
    while ((fileName = [childFilesEnumerator nextObject ]) != nil ){
        
        NSString * fileAbsolutePath = [folderPath stringByAppendingPathComponent :fileName];
        
        folderSize += [ self fileSizeAtPath :fileAbsolutePath];
        
    }
    
    return folderSize/( 1024.0 * 1024.0 );
    
}

// 显示缓存大小

- ( float )filePath
{
    
    NSString * cachPath = [ NSSearchPathForDirectoriesInDomains ( NSCachesDirectory , NSUserDomainMask , YES ) firstObject ];
    
    return [ self folderSizeAtPath :cachPath];
    
}

// 清理缓存
- ( void )clearFile
{
    
    
    NSString * cachPath = [ NSSearchPathForDirectoriesInDomains ( NSCachesDirectory , NSUserDomainMask , YES ) firstObject ];
    
    NSArray * files = [[ NSFileManager defaultManager ] subpathsAtPath :cachPath];
    
//    NSLog ( @"cachpath = %@" , cachPath);
    
    for ( NSString * p in files) {
        
        NSError * error = nil ;
        
        NSString * path = [cachPath stringByAppendingPathComponent :p];
        
        if ([[ NSFileManager defaultManager ] fileExistsAtPath :path]) {
            
            [[ NSFileManager defaultManager ] removeItemAtPath :path error :&error];
            
        }
        
    }
    [[SDImageCache sharedImageCache] clearDisk];
    [ self performSelectorOnMainThread : @selector (clearCachSuccess) withObject : nil waitUntilDone : YES ];
    
}

- ( void )clearCachSuccess
{
    
//    NSLog ( @" 清理成功 " );
    _clearCache.title =[ NSString stringWithFormat : @"清理缓存"];
    _clearCache.numLable.text = @"0.00M";
//    UIAlertView * alertView = [[ UIAlertView alloc ] initWithTitle: @"缓存已清理完毕" message :nil delegate : nil cancelButtonTitle :@"确定" otherButtonTitles : nil ];
//    
//    [alertView show ];
    UILabel *customView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 240, 40)];
    customView.backgroundColor = [UIColor whiteColor];
    customView.text = @"缓存已清理完毕";
    customView.textAlignment = NSTextAlignmentCenter;
    customView.layer.borderColor = [[UIColor blackColor] CGColor];
    customView.layer.borderWidth = 2;
    JCAlertView *_alert = [[JCAlertView alloc] initWithCustomView:customView dismissWhenTouchedBackground:NO];
    [_alert show];
    [_alert performSelector:@selector(dismissWithCompletion:) withObject:nil afterDelay:1.5];
    //[ _tableView reloadData ];//清理完之后重新导入数据
    
}


//符点助手
- (void)operatorAssistant
{

}
//给我们打分
- (void)givesScoreClick
{

}
//用户协定
- (void)userAgreementClick
{

}
//意见反馈
- (void)feedbackClick
{
    feedback_Controller *feedVC = [[feedback_Controller alloc]init];
    [self.navigationController pushViewController:feedVC animated:YES];

}
//推荐给好友
- (void)recommendFriends
{
   
    
    [UIView animateWithDuration:0.5 animations:^{
        shareView.frame = CGRectMake(0, self.view.height-self.view.height*0.4-10, self.view.width, self.view.height*0.4+10);
    }];
    
    


}
//取消分享
- (void)shareCancelClick
{
    [UIView animateWithDuration:0.5 animations:^{
        shareView.frame = CGRectMake(0, self.view.height*2, self.view.width, self.view.height*0.4);
    }];
}
//退出登录
- (void)exitClick
{
    EMError *error = [[EMClient sharedClient] logout:YES];
    if (!error) {
//        NSLog(@"退出成功");
    }
    AFNetworkReachabilityManager *netWorkManager = [AFNetworkReachabilityManager sharedManager];
    NSString *url = [NSString stringWithFormat:@"http://123.57.1.143/api/logout"];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain", nil];
    [manager POST:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [netWorkManager stopMonitoring];
        //将数据(uid和token)从本地清空
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults removeObjectForKey:@"uid"];
        [defaults removeObjectForKey:@"token"];
        [defaults removeObjectForKey:@"myDictionary"];
        [defaults synchronize];
        
        //删除缓存头像
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *headImageFilePath = [documentsDirectory stringByAppendingPathComponent:@"selfPhoto.jpg"];
        [fileManager removeItemAtPath:headImageFilePath error:nil];
        
        UILabel *customView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 240, 40)];
        customView.backgroundColor = [UIColor whiteColor];
        customView.text = @"已退出登录";
        customView.textAlignment = NSTextAlignmentCenter;
        customView.layer.borderColor = [[UIColor blackColor] CGColor];
        customView.layer.borderWidth = 2;
        JCAlertView *_alert = [[JCAlertView alloc] initWithCustomView:customView dismissWhenTouchedBackground:NO];
        [_alert show];
        [_alert performSelector:@selector(dismissWithCompletion:) withObject:nil afterDelay:1.5];
        
        MMDrawerController *controller = (MMDrawerController *)[AppDelegate shareDelegate].window.rootViewController;
        UITabBarController *tab = (UITabBarController *)controller.centerViewController;
        tab.selectedIndex = 0;
        [self.navigationController popViewControllerAnimated:YES];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
- (void)backTo
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:YES];
//    _setNameItem.headImage.image =
    self.tabBarController.tabBar.hidden = YES;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
